﻿using Models;
using Newtonsoft.Json;
using SIE.SCADA.Common.Log;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.ZemtDemo;
using SIE.SCADA.ZemtDemo.Common;
using SIE.SCADA.ZemtDemo.MqClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

namespace SCADA_DAQ.ZEMT.Server
{
    /// <summary>
    /// 配置上传
    /// </summary>
    public class MatcfgManager : MqMangerBase<MatcfgManager>
    {
        public string CurMatid { get; set; }
        public string linename = Env.LineName.Value;
        public event EventHandler MatcfgHandler;
       

        public MatcfgManager()
        {
            DataReceive();
        }

        //配置上传
        void Send(PmidRequest request)
        {
            var res = mqhelper.TopicExchangePublish(request, "ZEMT_MQ_EXCHANGE_GETTTSPLATE", "", $"GETTTSPLATE.{linename}"
                , true, false, true, false);
            if (res.Success)
            {
                System.Diagnostics.Debug.WriteLine("数据已推送完成的！");
            }
            else
                System.Diagnostics.Debug.WriteLine("数据推送失败！\n" + res.Message);
        }

        public void RequestMatcfg(string matid)
        {
            if (string.IsNullOrEmpty(matid)) return;
            var pmidRequest = new PmidRequest();
            var pmidItem = new PmidItem()
            {
                pmid = matid
            };
            pmidRequest.pmids.Add(pmidItem);
            Send(pmidRequest);
        }

        public override void Start()
        {
            base.Start();
        }

        void DataReceive()
        {
            ////配置上传接口
            //var res1 = mqhelper.TopicExchangeConsumer<MatcfgRoot>((data) =>
            //{
            //    if(data.retcode.Equals("1"))
            //    {
            //        SaveMatcfg(data);
            //        System.Diagnostics.Trace.WriteLine("配置结果接收成功");
            //    }
            //    return true;
            //}, "ZEMT_MQ_EXCHANGE_GETTTSPLATE", "ZEMT_MQ_SIE_GETTTSPLATE", $"GETTTSPLATE_SIE.{linename}", true, false, true, false);
        }

        void SaveMatcfg(MatcfgRoot data)
        {
            //scada_matcfg scada_Matcfg = null;
            var curMatcfg = new CurMatcfg();
            foreach (var pmdatas in data.pmdatas)
            {
                var version = pmdatas.version;
                var matid = pmdatas.pmid;
                using (var ctx = pgsql.GetClient())
                {
                    try
                    {
                        if (pgsql.DBClient is SmdcOrmClient ormClient)
                        {
                            var scada_Matcfg = ormClient.SqlSugarClient.Queryable<scada_matcfg>().Where(m => m.matid == matid).First();
                            var SCADA_MatCfgs = new List<scada_matcfg>();
                            foreach (var item in pmdatas.pmdatasItem)
                            {
                                scada_matcfg sCADA_MatCfg = new scada_matcfg();
                                sCADA_MatCfg.matid = item?.pmid;
                                var cname = item?.pmname;
                                if (item.pmname.Contains("$$"))
                                {
                                    cname = item.pmname.Replace("$$", @"\");
                                }
                                sCADA_MatCfg.cname = cname;
                                sCADA_MatCfg.childmatid = item?.mid;
                                var childname = item.mname;
                                if (item.mname.Contains("$$"))
                                {
                                    childname = item.mname.Replace("$$", @"\");
                                }
                                sCADA_MatCfg.childname = childname;
                                sCADA_MatCfg.index = item?.sort.ObjToInt();
                                sCADA_MatCfg.version = version;
                                sCADA_MatCfg.snmatch = item?.sn_onoff;
                                sCADA_MatCfg.batchmatch = item?.batch_onoff;
                                SCADA_MatCfgs.Add(sCADA_MatCfg);
                            }
                            if (scada_Matcfg == null)
                            {
                                ormClient.SqlSugarClient.Insertable<scada_matcfg>(SCADA_MatCfgs);
                            }
                            else if (scada_Matcfg?.version == version)
                            {

                            }
                            else
                            {
                                ormClient.SqlSugarClient.Deleteable<scada_matcfg>(m => m.matid == matid);
                                Thread.Sleep(50);
                                ormClient.SqlSugarClient.Insertable<scada_matcfg>(SCADA_MatCfgs);
                            }
                            curMatcfg.Matcfgs[matid] = version;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Warn(ex.Message);
                    }
                }
            }
            MatcfgHandler.Invoke(this, curMatcfg);
        }

        //test
        public void RevceiveTest()
        {
            TestConsumer<MatcfgRoot>((data) =>
            {
                SaveMatcfg(data);
                return true;
            });
        }

        private Result TestConsumer<T>(Func<T, bool> funReceived)
        {
            try
            {
                try
                {
                    string line;
                    // 从文件读取并显示行，直到文件的末尾 
                    line = File.ReadAllText(@"D:\jsonStr.txt");
                    if(line.Contains("\\")) line = line.Replace("\\", @"$");
                    var msgBody = Regex.Replace(line, @"(\\[^bfrnt\\/'\""])", "\\$1");
                    var data = JsonConvert.DeserializeObject<T>(msgBody);
                    funReceived.Invoke(data);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex);
                    //LoggerHelper.Logger.CreatLogger("Service").Error(ex);
                    //throw;
                }
                System.Diagnostics.Trace.WriteLine("==============TopicExchangeConsumer Start Running ！==============");
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
            finally
            {
                //if (channel != null) channel.Close();
                //if (conn != null) conn.Close();
            }
        }

        public class PmidItem
        {
            public string pmid { get; set; }
        }

        public class PmidRequest
        {
            public List<PmidItem> pmids { get; set; }

            public PmidRequest()
            {
                pmids = new List<PmidItem>();
            }
        }

        public class CurMatcfg:EventArgs
        {

            public Dictionary<string, string> Matcfgs = new Dictionary<string, string>();
        }


    }
}
